// import axios from 'axios'
// import Vue from 'vue'

let http = axios.create({
  baseURL: '',
  withCredentials: false
})

/**
 * 对axios进行二次封装
 * @param http请求方法
 * @param 后台接口地址
 * @param 提交的参数
 * @return Promise: data或者error
 * */
function apiAxios (method, url, param, headers = null) {
  const token = url.includes('api.map.baidu.com') ? null : sessionStorage['token']
  const defaultHeaders = token ? {
    token
  } : null
  let mixHeaders = {...defaultHeaders, ...headers}

  // code = 1 返回正确的结果
  const SUCCESS_CODE = 1
  const FAIL_TOKEN_invalid  = 10001
  const FAIL_STATUS_Expired  = 10002

  return new Promise((resolve, reject) => {
    http({
      method: method,
      url: url,
      data: method === 'POST' || method === 'PUT' ? param : null,
      params: method === 'GET' || method === 'DELETE' ? param : null,
      headers: mixHeaders
    }).then(function (_res) {
      if (_res.status >= 200 && _res.status < 300) {
        const res = _res.data
        if (res.code !== SUCCESS_CODE) {
          reject(new Error(`${res.message || res.msg}`))
        } else {
          const data = res.data || res.result
          resolve(data)
        }
      }
    }).catch(err => {
      reject(err)
    })
  })
}

const $http = {
  get (url, param, headers) {
    return apiAxios('GET', url, param, headers)
  },
  post (url, param, headers) {
    return apiAxios('POST', url, param, headers)
  },
  put (url, param, headers) {
    return apiAxios('PUT', url, param, headers)
  },
  delete (url, param, headers) {
    return apiAxios('DELETE', url, param, headers)
  }
}
Vue.prototype.$http = $http
export default $http

